package com.cloudlinkscm.base.authcenter.shiro;

import com.cloudlinkscm.base.authcenter.dao.UserAccountDao;
import com.cloudlinkscm.base.authcenter.exception.UserAccountNotFindException;
import com.cloudlinkscm.base.authcenter.model.UserAccount;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

/**
 * @author : tac
 * @date : 31/07/2017
 */

public class CustomRealm extends AuthorizingRealm {
    private UserAccountDao userAccountDao;

    public void setUserAccountDao(UserAccountDao userAccountDao) {
        this.userAccountDao = userAccountDao;
    }

    @Override
    public String getName() {
        return "custom realm";
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //todo:: 不需要在鉴权中心做授权操作
        throw new NotImplementedException();
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        if(userAccountDao == null){
            throw new NullPointerException("userAccountDao");
        }

        UsernamePasswordToken t = (UsernamePasswordToken) token;
        UserAccount account = userAccountDao.selectByUsername(t.getUsername());
        if (account == null) {
        	throw new UserAccountNotFindException();
        }
        PrincipalCollection principals = new SimplePrincipalCollection(account, getName());
        return new SimpleAccount(principals, account.getPassword(), getName());
    }
}
